package com.macro.mall.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.common.util.DateUtil;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.dao.HomeDao;
import com.macro.mall.portal.dao.PmsProductCategoryGoodsDao;
import com.macro.mall.portal.dao.PortalSkuStockDao;
import com.macro.mall.portal.dao.PortalStoreDao;
import com.macro.mall.portal.domain.*;
import com.macro.mall.portal.dto.PmsProductDto;
import com.macro.mall.portal.dto.PmsProductParam;
import com.macro.mall.portal.service.HomeService;
import com.macro.mall.portal.service.PmsPortalProductService;
import com.macro.mall.portal.service.UmsMemberService;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.entity.MarketSmsRoundProduct;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页内容管理Service实现类
 * Created by macro on 2019/1/28.
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Value("${distance.val}")
    private Double distance;
    @Autowired
    private SmsHomeAdvertiseMapper advertiseMapper;
    @Autowired
    private HomeDao homeDao;
    @Autowired
    private SmsFlashPromotionMapper flashPromotionMapper;
    @Autowired
    private SmsFlashPromotionSessionMapper promotionSessionMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private CmsSubjectMapper subjectMapper;
    @Autowired
    private UmsStoreMapper storeMapper;
    @Autowired
    private PortalStoreDao portalStoreDao;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private  PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private  PortalSkuStockDao portalSkuStockDao;
    @Autowired
    private PmsPortalProductService pmsPortalProductService;
    @Autowired
    private PmsMemberPriceMapper priceMapper;
    @Autowired
    private PmsProductCategoryGoodsDao goodsDao;
    @Autowired
    private RedisService redisService;
    @Override
    public HomeContentResult content(Long storeId,Double lon,Double lat) {
       HomeContentResult result = new HomeContentResult();
        UmsStore store = null;
        if(storeId!=null){
            store = this.storeMapper.selectByPrimaryKey(storeId);
        }else{
            store = this.portalStoreDao.getNearbyStore(lat, lon,null);
        }
        //获取当前登录用户id
        List<PmsProductCategory> categoryList = getCategoryList(store.getId());
        List<PmsProductCategoryGoods> categoryGoodsList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(categoryList)){
            for (PmsProductCategory category: categoryList) {
                List<PmsProductCategoryGoods> goods = this.goodsDao.getGoods(storeId, null, category.getId());
                if (!CollectionUtils.isEmpty(goods)) {
                    for (PmsProductCategoryGoods good : goods){
                        List<PmsProductParam> list = good.getList();
                        if (!CollectionUtils.isEmpty(list)) {
                            for (PmsProductParam pmsProductParam: list) {
                                PmsSkuStockExample stockExample = new PmsSkuStockExample();
                                stockExample.createCriteria().andProductIdEqualTo(pmsProductParam.getId());
                                List<PmsSkuStock> pmsSkuStocks = pmsSkuStockMapper.selectByExample(stockExample);
                                if (!CollectionUtils.isEmpty(pmsSkuStocks)) {
                                    Optional<PmsSkuStock> min = pmsSkuStocks.stream().min(Comparator.comparing(PmsSkuStock::getPrice));
                                    PmsSkuStock pmsSkuStock = null;
                                    if(min.isPresent()){
                                        pmsSkuStock = min.get();
                                    }else {
                                        pmsSkuStock = pmsSkuStocks.get(0);
                                    }
                                    PmsMemberPriceExample priceExample = new PmsMemberPriceExample();
                                    priceExample.createCriteria().andProductStockIdEqualTo(pmsSkuStock.getId());
                                    List<PmsMemberPrice> pmsMemberPrices = priceMapper.selectByExample(priceExample);
                                    pmsProductParam.setMemberPrice(pmsMemberPrices.get(0).getMemberPrice());
                                    pmsProductParam.setPrice(pmsSkuStock.getPrice());
                                }
                            }
                        }

                    }
                }
                categoryGoodsList.addAll(goods);
            }
        }
        result.setCategoryGoodsList(categoryGoodsList);//会员价在这里
        //获取首页广告
        result.setAdvertiseList(getHomeAdvertiseList(store.getId()));
        //获取分类
        PageHelper.startPage(1, 9);
        result.setCategoryList(categoryList);
        PageHelper.clearPage();
        //门店
        result.setUmsStore(store);
        //获取秒杀信息
        List keys = this.redisService.keys(RedisKey.ROUND_STARTING_KEY);
        result.setSecKillProducts(this.getProducts(store, keys,MarketSmsRound.TYPE.SEC_KILL.VALUE));
        //获取团购商品信息
        result.setGroupBuyProducts(this.getProducts(store, keys,MarketSmsRound.TYPE.GROUP_BUYING.VALUE));
//        //获取新品推荐
//        result.setNewProductList(homeDao.getNewProductList(0, 4));
        //获取人气推荐
        List<PmsProduct> hotProductList = this.homeDao.getHotProductList(0, 4, store.getId());
        List<PmsProductDto> memberPrice = pmsPortalProductService.getMemberPrice(hotProductList, store.getId());
        result.setHotProductList(memberPrice);
        //首页显示组合商品
        result.setCombinedPmsProductList(this.getCombinedPmsProductList(store.getId()));
        PageHelper.clearPage();
        return result;
    }

    /**
     * 获取活动商品展示列表
     * @param store
     * @param keys
     */
    private List<PmsProductDto> getProducts(UmsStore store, List keys,Integer type) {
        List<PmsProductDto> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(keys)){
            for (Object o: keys) {
                if(o instanceof MarketSmsRound){
                    MarketSmsRound marketSmsRound = (MarketSmsRound)o;
                    if(marketSmsRound.getUserId().equals(store.getUserId())){
                        if(marketSmsRound.getType().equals(type)){
                            List keys1 = this.redisService.keys(RedisKey.ROUND_SKU_STOCK_KEY);
                            List<MarketSmsRoundProduct> products = new ArrayList<>();
                            if(!CollectionUtils.isEmpty(keys1)){
                                for (Object obj:keys1) {
                                    if(obj instanceof  MarketSmsRoundProduct){
                                        MarketSmsRoundProduct product = (MarketSmsRoundProduct)obj;
                                        if(product.getRoundId().equals(marketSmsRound.getId())){
                                            products.add(product);

                                        }
                                    }
                                }
                            }
                            if(!CollectionUtils.isEmpty(products)){
                                Map<Long, List<MarketSmsRoundProduct>> map = products.stream().collect(Collectors.groupingBy(MarketSmsRoundProduct::getProductId));
                                for(Map.Entry<Long, List<MarketSmsRoundProduct>> entry: map.entrySet()){
                                    if(list.size()<3){
                                        Long productId = entry.getKey();
                                        List<MarketSmsRoundProduct> value = entry.getValue();
                                        PmsProduct pmsProduct = this.productMapper.selectByPrimaryKey(productId);
                                        PmsProductDto dto = new PmsProductDto();
                                        BeanUtils.copyProperties(pmsProduct,dto);
                                        BigDecimal min = value.stream().filter(e -> e.getActivityPrice() != null).map(MarketSmsRoundProduct::getActivityPrice).min((e1, e2) -> e1.compareTo(e2)).get();
                                        dto.setActivityPrice(min);
                                        dto.setRoundId(marketSmsRound.getId());
                                        list.add(dto);
                                    }else{
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<CombinedPmsProduct> getCombinedPmsProductList(Long storeId) {
        List<CombinedPmsProduct> combinedPmsProductList = new ArrayList<>();
        PmsProductExample example = new PmsProductExample();
        example.createCriteria()
                .andStoreIdEqualTo(storeId)
                .andTypeEqualTo(1)
//                .andRecommandStatusEqualTo(1)
                .andDeleteStatusEqualTo(0)
                .andVerifyStatusEqualTo(1)
                .andPublishStatusEqualTo(1);
        List<PmsProduct> pmsProducts = this.productMapper.selectByExample(example);
        List<Long> ids = pmsProducts.stream().map(PmsProduct::getId).collect(Collectors.toList());
        if(ids.size()>4){
            ids = ids.subList(0,4);
        }
        if(!CollectionUtils.isEmpty(ids)){
            PmsSkuStockExample stockExample = new PmsSkuStockExample();
            stockExample.createCriteria().andStoreIdEqualTo(storeId)
                    .andProductIdIn(ids);
            List<PmsSkuStock> pmsSkuStocks = this.pmsSkuStockMapper.selectByExample(stockExample);
            List<Long> collect = pmsSkuStocks.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(collect)){
                combinedPmsProductList= this.portalSkuStockDao.queryProductsByCombineParentIds(collect);
            }else{
                combinedPmsProductList = new ArrayList<>();
            }
        }
        return combinedPmsProductList;
    }

    private List<PmsProductCategory> getCategoryList(Long storeId) {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria()
                .andShowStatusEqualTo(1)
                .andLevelEqualTo(0)
                .andStoreIdEqualTo(storeId);
        example.setOrderByClause("sort");
        return productCategoryMapper.selectByExample(example);
    }

    @Override
    public List<PmsProduct> recommendProductList(Long storeId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria()
                .andDeleteStatusEqualTo(0)
                .andPublishStatusEqualTo(1)
                .andVerifyStatusEqualTo(1)
                .andRecommandStatusEqualTo(1)
                .andStoreIdEqualTo(storeId);
        return productMapper.selectByExample(example);
    }


    @Override
    public List<PmsProductCategory> getProductCateList(Long parentId) {
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria()
                .andShowStatusEqualTo(1)
                .andParentIdEqualTo(parentId);
        example.setOrderByClause("sort desc");
        return productCategoryMapper.selectByExample(example);
    }

    @Override
    public List<CmsSubject> getSubjectList(Long cateId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        CmsSubjectExample example = new CmsSubjectExample();
        CmsSubjectExample.Criteria criteria = example.createCriteria();
        criteria.andShowStatusEqualTo(1);
        if (cateId != null) {
            criteria.andCategoryIdEqualTo(cateId);
        }
        return subjectMapper.selectByExample(example);
    }

    @Override
    public CommonPage<PmsProduct> hotProductList(long storeId,Integer pageNum, Integer pageSize) {
//        int offset = pageSize * (pageNum - 1);
//        return homeDao.getHotProductList(offset, pageSize, storeId);
        PageHelper.startPage(pageNum,pageSize);
        PmsProductExample example = new PmsProductExample();
        //推荐状态、上架
        example.createCriteria().andStoreIdEqualTo(storeId).andRecommandStatusEqualTo(1).andPublishStatusEqualTo(1);
        CommonPage<PmsProduct> result = new CommonPage<>();
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        if(pmsProducts != null && pmsProducts.size() > 0){
            CommonPage<PmsProduct> pmsProductCommonPage = CommonPage.restPage(pmsProducts);
            return pmsProductCommonPage;
        }else {
            return result;
        }
    }

    @Override
    public List<PmsProduct> newProductList(Integer pageNum, Integer pageSize) {
        int offset = pageSize * (pageNum - 1);
        return homeDao.getNewProductList(offset, pageSize);
    }

    @Override
    public List<PmsProduct> getCarouselProduct() {
        UmsMember currentMember = memberService.getCurrentMember();
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andStoreIdEqualTo(currentMember.getStoreId());
        //按照促销时间排序，取后3个
        example.setOrderByClause("promotion_start_time");
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        //轮播图显示几条商品的计数
        int count = 0;
        List<PmsProduct> result = new ArrayList<>();
        if (pmsProducts != null && pmsProducts.size() > 0) {
            for (int i = pmsProducts.size(); i == 0; i--) {
                result.add(pmsProducts.get(i));
                count++;
                if (count == 3) {
                    break;
                }
            }
        }
        return result;
    }

    //根据用户信息，判断当前用户是否绑定店铺
    @Override
    public List<UmsStore> getStoreByUser(UmsMember member, Double lat, Double lon) {
        List<UmsStore> result = new ArrayList<>();
        if(null == member.getStoreId() || member.getStoreId() == 0){
            //未绑定店铺
            return result;
        }else{
            //已绑定店铺
            UmsStore store = storeMapper.selectByPrimaryKey(member.getStoreId());
            result.add(store);
        }
        return result;
    }

    @Override
    public CommonResult<UmsStore> getStoreInfo() {
        UmsMember currentMember = memberService.getCurrentMember();
        UmsStore store = storeMapper.selectByPrimaryKey(currentMember.getStoreId());
        return CommonResult.success(store);
    }

    private HomeFlashPromotion getHomeFlashPromotion() {
        HomeFlashPromotion homeFlashPromotion = new HomeFlashPromotion();
        //获取当前秒杀活动
        Date now = new Date();
        SmsFlashPromotion flashPromotion = getFlashPromotion(now);
        if (flashPromotion != null) {
            //获取当前秒杀场次
            SmsFlashPromotionSession flashPromotionSession = getFlashPromotionSession(now);
            if (flashPromotionSession != null) {
                homeFlashPromotion.setStartTime(flashPromotionSession.getStartTime());
                homeFlashPromotion.setEndTime(flashPromotionSession.getEndTime());
                //获取下一个秒杀场次
                SmsFlashPromotionSession nextSession = getNextFlashPromotionSession(homeFlashPromotion.getStartTime());
                if (nextSession != null) {
                    homeFlashPromotion.setNextStartTime(nextSession.getStartTime());
                    homeFlashPromotion.setNextEndTime(nextSession.getEndTime());
                }
                //获取秒杀商品
                List<FlashPromotionProduct> flashProductList = homeDao.getFlashProductList(flashPromotion.getId(), flashPromotionSession.getId());
                homeFlashPromotion.setProductList(flashProductList);
            }
        }
        return homeFlashPromotion;
    }

    //获取下一个场次信息
    private SmsFlashPromotionSession getNextFlashPromotionSession(Date date) {
        SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample();
        sessionExample.createCriteria()
                .andStartTimeGreaterThan(date);
        sessionExample.setOrderByClause("start_time asc");
        List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample);
        if (!CollectionUtils.isEmpty(promotionSessionList)) {
            return promotionSessionList.get(0);
        }
        return null;
    }

    private List<SmsHomeAdvertise> getHomeAdvertiseList(Long storeId) {
        SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample();
        example.createCriteria().andTypeEqualTo(1).andStatusEqualTo(1).andStoreIdEqualTo(storeId);
        example.setOrderByClause("sort desc");
        List<SmsHomeAdvertise> smsHomeAdvertises = advertiseMapper.selectByExample(example);
        List<SmsHomeAdvertise> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(smsHomeAdvertises)) {
            for (SmsHomeAdvertise sms : smsHomeAdvertises){
                if(sms.getUrl() != null && !"".equals(sms.getUrl())){
                    PmsProduct product = productMapper.selectByPrimaryKey(Long.parseLong(sms.getUrl()));
                    if(product.getDeleteStatus().equals(1) || (product.getPublishStatus() != null && product.getPublishStatus().equals(0))){
                        //商品已删除
                        continue;
                    }else{
                        //广告轮播的开始时间和结束时间
                        Date startTime = sms.getStartTime();
                        Date endTime = sms.getEndTime();
                        Date date = new Date();
                        if (startTime.before(date) && endTime.after(date)) {
                            result.add(sms);
                        }
                    }
                }
            }
        }
        return result;
    }

    //根据时间获取秒杀活动
    private SmsFlashPromotion getFlashPromotion(Date date) {
        Date currDate = DateUtil.getDate(date);
        SmsFlashPromotionExample example = new SmsFlashPromotionExample();
        example.createCriteria()
                .andStatusEqualTo(1)
                .andStartDateLessThanOrEqualTo(currDate)
                .andEndDateGreaterThanOrEqualTo(currDate);
        List<SmsFlashPromotion> flashPromotionList = flashPromotionMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(flashPromotionList)) {
            return flashPromotionList.get(0);
        }
        return null;
    }

    //根据时间获取秒杀场次
    private SmsFlashPromotionSession getFlashPromotionSession(Date date) {
        Date currTime = DateUtil.getTime(date);
        SmsFlashPromotionSessionExample sessionExample = new SmsFlashPromotionSessionExample();
        sessionExample.createCriteria()
                .andStartTimeLessThanOrEqualTo(currTime)
                .andEndTimeGreaterThanOrEqualTo(currTime);
        List<SmsFlashPromotionSession> promotionSessionList = promotionSessionMapper.selectByExample(sessionExample);
        if (!CollectionUtils.isEmpty(promotionSessionList)) {
            return promotionSessionList.get(0);
        }
        return null;
    }
}
